import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:developer' as developer;
import 'package:provider/provider.dart';
import 'package:camera/camera.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image/image.dart' as img;
import 'dart:io';
import 'dart:math' as math;
import 'dart:typed_data';
import '../providers/light_provider.dart';
import '../providers/color_provider.dart';
import 'settings_screen.dart';

// 日志工具函数
void _log(String message, {String? name, Object? error, StackTrace? stackTrace}) {
  if (kDebugMode) {
    developer.log(
      message,
      name: name ?? 'App',
      error: error,
      stackTrace: stackTrace,
    );
  }
}

// 顶级函数用于图片处理
Uint8List processImage(Uint8List imageBytes) {
  try {
    _log('开始处理图片', name: 'ImageProcess');
    _log('原始图片大小: ${imageBytes.length} bytes', name: 'ImageProcess');

    final img.Image? capturedImage = img.decodeImage(imageBytes);
    if (capturedImage == null) {
      _log('解码图片失败', name: 'ImageProcess', error: 'Decoded image is null');
      throw Exception('Failed to decode image');
    }
    _log('原始图片尺寸: ${capturedImage.width}x${capturedImage.height}', name: 'ImageProcess');

    // 水平翻转图片
    final img.Image flippedImage = img.flipHorizontal(capturedImage);
    _log('完成图片翻转', name: 'ImageProcess');

    // 计算目标尺寸
    final int maxDimension = 1920;
    final int originalWidth = flippedImage.width;
    final int originalHeight = flippedImage.height;

    double scale = 1.0;
    if (originalWidth > maxDimension || originalHeight > maxDimension) {
      scale = maxDimension / math.max(originalWidth, originalHeight);
    }

    final int targetWidth = (originalWidth * scale).round();
    final int targetHeight = (originalHeight * scale).round();

    _log('目标尺寸: ${targetWidth}x${targetHeight}, 缩放比例: $scale', name: 'ImageProcess');

    // 调整图片大小
    final img.Image resizedImage = img.copyResize(
        flippedImage,
        width: targetWidth,
        height: targetHeight,
        interpolation: img.Interpolation.linear
    );
    _log('完成图片缩放', name: 'ImageProcess');

    // 编码为JPEG
    final Uint8List jpegBytes = Uint8List.fromList(img.encodeJpg(resizedImage, quality: 95));
    _log('完成JPEG编码，最终大小: ${jpegBytes.length} bytes', name: 'ImageProcess');

    return jpegBytes;
  } catch (e, stackTrace) {
    _log(
        '图片处理失败',
        name: 'ImageProcess',
        error: e,
        stackTrace: stackTrace
    );
    throw Exception('Image processing failed: $e');
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  CameraController? _cameraController;
  bool _isMirrorOn = false;
  bool _isCameraInitialized = false;
  bool _isSaving = false;

  @override
  void dispose() {
    _cameraController?.dispose();
    super.dispose();
  }

  Future<void> _initializeCamera() async {
    final cameras = await availableCameras();
    final frontCamera = cameras.firstWhere(
          (camera) => camera.lensDirection == CameraLensDirection.front,
      orElse: () => cameras.first,
    );

    _cameraController = CameraController(
      frontCamera,
      ResolutionPreset.medium,
      enableAudio: false,
    );

    try {
      await _cameraController!.initialize();
      if (mounted) {
        setState(() {
          _isCameraInitialized = true;
        });
      }
    } catch (e) {
      _log('Error initializing camera: $e');
    }
  }

  Future<void> _toggleMirror() async {
    if (_isMirrorOn) {
      setState(() {
        _isMirrorOn = false;
        _isCameraInitialized = false;
      });
      await _cameraController?.dispose();
      _cameraController = null;
    } else {
      final status = await Permission.camera.request();
      if (status.isGranted) {
        await _initializeCamera();
        setState(() {
          _isMirrorOn = true;
        });
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('需要相机权限才能使用镜子功能')),
          );
        }
      }
    }
  }

  Future<void> _saveImage() async {
    if (_cameraController == null || !_isCameraInitialized) return;

    try {
      setState(() {
        _isSaving = true;
      });

      _log('开始保存图片', name: 'ImageSave');

      // 捕获图像
      final XFile image = await _cameraController!.takePicture();
      _log('完成图片捕获: ${image.path}', name: 'ImageSave');

      // 读取图片数据
      final File imageFile = File(image.path);
      final Uint8List imageBytes = await imageFile.readAsBytes();
      _log('读取原始图片: ${imageBytes.length} bytes', name: 'ImageSave');

      // 在独立的 isolate 中处理图片
      _log('开始异步处理图片', name: 'ImageSave');
      final Uint8List processedImageBytes = await compute(processImage, imageBytes);
      _log('完成图片处理: ${processedImageBytes.length} bytes', name: 'ImageSave');

      // 保存处理后的图片
      final result = await ImageGallerySaver.saveImage(
          processedImageBytes,
          quality: 100,
          name: "FillLight_${DateTime.now().millisecondsSinceEpoch}"
      );
      _log('保存结果: $result', name: 'ImageSave');

      // 清理临时文件
      await imageFile.delete();
      _log('清理临时文件完成', name: 'ImageSave');

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(result['isSuccess'] ? '图片已保存到相册' : '保存失败'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } catch (e, stackTrace) {
      _log(
          '保存图片失败',
          name: 'ImageSave',
          error: e,
          stackTrace: stackTrace
      );

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保存失败: ${e.toString()}'),
            duration: const Duration(seconds: 2),
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSaving = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final cameraSize = screenSize.width * 0.6;
    final topPadding = MediaQuery.of(context).padding.top;

    return Consumer2<LightProvider, ColorProvider>(
      builder: (context, lightProvider, colorProvider, child) {
        final bool showSaveButton = _isMirrorOn && _isCameraInitialized && !lightProvider.showUI;

        return Scaffold(
          backgroundColor: colorProvider.currentColor,
          body: Stack(
            children: [
              Column(
                children: [
                  // 上部分 - 固定高度区域
                  Container(
                    height: cameraSize + topPadding + 32, // 相机预览高度 + 顶部padding + 额外间距
                    child: Stack(
                      children: [
                        // 左侧按钮组
                        Positioned(
                          top: topPadding + 16,
                          left: 16,
                          child: Column(
                            children: [
                              // 隐藏按钮 - 始终显示
                              Container(
                                width: 50,
                                height: 50,
                                margin: const EdgeInsets.only(bottom: 16),
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Colors.white,
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.1),
                                      blurRadius: 8,
                                      spreadRadius: 2,
                                    ),
                                  ],
                                ),
                                child: IconButton(
                                  icon: Icon(
                                    lightProvider.showUI ? Icons.visibility_off : Icons.visibility,
                                    color: Colors.grey[600],
                                    size: 24,
                                  ),
                                  onPressed: () => lightProvider.toggleUIVisibility(),
                                ),
                              ),
                              // 镜子按钮 - 根据showUI显示/隐藏
                              if (lightProvider.showUI)
                                Container(
                                  width: 50,
                                  height: 50,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: _isMirrorOn ? Colors.pink[100] : Colors.white,
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.black.withOpacity(0.1),
                                        blurRadius: 8,
                                        spreadRadius: 2,
                                      ),
                                    ],
                                  ),
                                  child: IconButton(
                                    icon: Icon(
                                      _isMirrorOn ? Icons.face_retouching_natural : Icons.face,
                                      size: 30,
                                      color: _isMirrorOn ? Colors.pink[300] : Colors.grey[600],
                                    ),
                                    onPressed: _toggleMirror,
                                  ),
                                ),
                            ],
                          ),
                        ),

                        // 相机预览 - 始终显示（如果开启）
                        if (_isMirrorOn && _isCameraInitialized && _cameraController != null)
                          Positioned(
                            top: topPadding + 16,
                            left: (screenSize.width - cameraSize) / 2,
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(16),
                              child: Container(
                                width: cameraSize,
                                height: cameraSize,
                                child: Transform.scale(
                                  scale: 1.5,
                                  child: Center(
                                    child: CameraPreview(_cameraController!),
                                  ),
                                ),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),

                  // 下部分 - 可滚动的操作区域
                  if (lightProvider.showUI)
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: const BorderRadius.vertical(
                            top: Radius.circular(32),
                          ),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.1),
                              blurRadius: 8,
                              offset: const Offset(0, -2),
                            ),
                          ],
                        ),
                        child: SingleChildScrollView(
                          padding: const EdgeInsets.fromLTRB(24, 24, 24, 0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 预设颜色
                              Text(
                                '内置色系',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.grey[800],
                                ),
                              ),
                              const SizedBox(height: 16),
                              _buildPresetColors(context, colorProvider),
                              const SizedBox(height: 24),

                              // 控制滑块
                              Text(
                                '调节控制',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.grey[800],
                                ),
                              ),
                              const SizedBox(height: 16),
                              SliderSection(
                                title: '色调',
                                icon: Icons.palette,
                                value: lightProvider.hue,
                                min: 0,
                                max: 360,
                                onChanged: (value) {
                                  lightProvider.setHue(value);
                                  colorProvider.setHSB(hue: value);
                                },
                              ),
                              SliderSection(
                                title: '饱和度',
                                icon: Icons.water_drop,
                                value: lightProvider.saturation * 100,
                                min: 0,
                                max: 100,
                                onChanged: (value) {
                                  lightProvider.setSaturation(value / 100);
                                  colorProvider.setHSB(saturation: value / 100);
                                },
                              ),
                              SliderSection(
                                title: '明度',
                                icon: Icons.brightness_6,
                                value: lightProvider.brightness * 100,
                                min: 0,
                                max: 100,
                                onChanged: (value) {
                                  lightProvider.setBrightness(value / 100);
                                  colorProvider.setHSB(brightness: value / 100);
                                },
                              ),
                              SliderSection(
                                title: '屏幕亮度',
                                icon: Icons.brightness_7,
                                value: lightProvider.screenBrightness * 100,
                                min: 0,
                                max: 100,
                                onChanged: (value) {
                                  lightProvider.setScreenBrightness(value / 100);
                                },
                              ),

                              // 重置按钮
                              Center(
                                child: Padding(
                                  padding: EdgeInsets.only(
                                    top: 24,
                                    bottom: MediaQuery.of(context).padding.bottom + 24,
                                  ),
                                  child: TextButton.icon(
                                    onPressed: () => lightProvider.reset(),
                                    icon: const Icon(Icons.refresh),
                                    label: const Text('重置'),
                                    style: TextButton.styleFrom(
                                      foregroundColor: Colors.pink[300],
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 24,
                                        vertical: 12,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                ],
              ),

              // 保存按钮 - 当相机开启且UI隐藏时显示
              if (showSaveButton)
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: screenSize.height * 0.25, // 从底部向上25%的位置
                  child: Center(
                    child: Container(
                      width: 80, // 增大按钮尺寸
                      height: 80,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.2),
                            blurRadius: 12,
                            spreadRadius: 4,
                          ),
                        ],
                      ),
                      child: IconButton(
                        icon: _isSaving
                            ? const SizedBox(
                          width: 32,
                          height: 32,
                          child: CircularProgressIndicator(
                            strokeWidth: 3,
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.pink),
                          ),
                        )
                            : const Icon(
                          Icons.photo_camera,
                          color: Colors.pink,
                          size: 40,
                        ),
                        onPressed: _isSaving ? null : _saveImage,
                      ),
                    ),
                  ),
                ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildPresetColors(BuildContext context, ColorProvider colorProvider) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // const Text(
        //   '内置色系',
        //   style: TextStyle(
        //     fontSize: 16,
        //     fontWeight: FontWeight.w500,
        //   ),
        // ),
        const SizedBox(height: 16),
        Wrap(
          spacing: 12,
          runSpacing: 12,
          children: colorProvider.predefinedColors.map((color) {
            final bool isSelected = color == colorProvider.currentColor;
            return GestureDetector(
              onTap: () {
                // 更新ColorProvider的颜色
                colorProvider.setColor(color);

                // 获取HSV值
                final HSVColor hsvColor = HSVColor.fromColor(color);

                // 更新LightProvider的值
                final lightProvider = Provider.of<LightProvider>(context, listen: false);
                lightProvider.setHue(hsvColor.hue);
                lightProvider.setSaturation(hsvColor.saturation);
                lightProvider.setBrightness(hsvColor.value);
              },
              child: Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: color,
                  borderRadius: BorderRadius.circular(25),
                  border: Border.all(
                    color: isSelected ? Colors.pink[300]! : Colors.grey[300]!,
                    width: 2,
                  ),
                  boxShadow: isSelected
                      ? [
                    BoxShadow(
                      color: Colors.pink[100]!.withOpacity(0.5),
                      blurRadius: 8,
                      spreadRadius: 2,
                    )
                  ]
                      : null,
                ),
              ),
            );
          }).toList(),
        ),
      ],
    );
  }
}

class SliderSection extends StatelessWidget {
  final String title;
  final IconData icon;
  final double value;
  final double min;
  final double max;
  final Function(double) onChanged;

  const SliderSection({
    Key? key,
    required this.title,
    required this.icon,
    required this.value,
    required this.min,
    required this.max,
    required this.onChanged,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Icon(icon, color: Colors.pink[300], size: 20),
                    const SizedBox(width: 8),
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
                Text(
                  '${value.toStringAsFixed(0)}',
                  style: TextStyle(
                    color: Colors.pink[300],
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            SliderTheme(
              data: SliderTheme.of(context).copyWith(
                activeTrackColor: Colors.pink[300],
                inactiveTrackColor: Colors.pink[100],
                thumbColor: Colors.pink[300],
                overlayColor: Colors.pink[300]?.withOpacity(0.2),
                trackHeight: 4,
              ),
              child: Slider(
                value: value,
                min: min,
                max: max,
                onChanged: onChanged,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
